const path = require('path')
const webpack = require('webpack')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const VueWebpackPlugin = require('vue-loader/lib/plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')

module.exports = {
  entry: './src/main.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[hash:8].bundle.js',
    chunkFilename: '[hash:8].chunk.js'
  },
  mode: 'development',
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.(js|vue)$/,
        loader: 'eslint-loader', // 根据eslint去检测js和vue中的语法
        exclude: /node_modules/ // 不去自动检测node_modules中的文件
      },
      {
        test: /\.(less|css)$/, // 编译 less 和 css 语法， use数组中是按顺序执行的
        use: [
          'vue-style-loader',
          {
            loader: 'css-loader',
            options: {
              // 开启 CSS Modules, 用于模块化和组合 CSS 的系统
              modules: true
            }
          },
          'less-loader'
        ]
      },
      {
        test: /\.svg$/,
        use: [
          {
            loader: require.resolve('@svgr/webpack'),
            options: {
              svgoConfig: { plugins: [{ removeViewBox: false }] },
              name: 'static/svg/[name].[hash:8].[ext]'
            }
          },
          {
            loader: require.resolve('file-loader')
          }
        ]
      },
      {
        test: /\.(png|jpe?g|gif)$/, // 编译图片文件
        loader: 'url-loader',
        options: {
          limit: 10000,
          esModule: false,
          name: 'img/[name].[hash:6].[ext]'
        }
      },
      {
        test: /.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, // 编译音频文件
        loader: 'url-loader',
        options: {
          limit: 10000,
          esModule: false,
          name: 'media/[name].[hash:6].[ext]'
        }
      },
      {
        test: /.(woff2?|eot|ttf|otf)(\?.*)?$/, // 编译字体文件
        loader: 'url-loader',
        options: {
          limit: 10000,
          esModule: false,
          name: 'fonts/[name].[hash:6].[ext]'
        }
      },
      {
        test: /\.vue$/, // 对当前路径下的src下的所有vue文件编译
        loader: 'vue-loader',
        exclude: '/node_modules/',
        include: path.join(__dirname, 'src')
      },
      {
        test: /\.js$/, // 对js文件进行es6转es5
        loader: 'babel-loader',
        exclude: '/node_modules/',
        include: path.join(__dirname, 'src')
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: path.resolve(__dirname, 'public'),
          to: 'public'
        }
      ]
    }),
    new webpack.ProvidePlugin({ // 兼容第三方插件到浏览器， 将
      _: 'lodash'
    }),
    new HtmlWebpackPlugin({ // 使旧版本浏览器支持 import() 和 require.ensure()
      // BASE_URL: './',
      title: 'Webpack Vue Sample',
      template: 'public/index.html'
    }),
    new VueWebpackPlugin()
  ]
}
